package basics.jvm;

/**
 * 加深对 字符串常量池 的理解
 * @author or2
 * @Description 深入了解JVM
 * @create 2021年08月31日 时间: 16:36
 */
public class ConstantString {
    public static void main(String[] args) {
        String str1 = new StringBuilder("计算机").append("技术").toString();
        System.out.println(str1 == str1.intern());

        String str2 = new StringBuilder("ja").append("va").toString();
        System.out.println(str2 == str2.intern());

//        优化方面
        String a = "orz2";
        final String b = "orz";
        final String f = getString();
        String c = "orz";
        String d = b + 2;
        String e = c + 2;
        String g = f + 2;
        System.out.println("(a == d): " + (a == d));
        System.out.println("(a == e): " + (a == e));
        System.out.println("(a == e.intern()): " + (a == e.intern()));
        System.out.println("(a == f): " + (a == f));

//        jdk 在 Integer 中'享元模式'的应用
        Integer int1 = Integer.valueOf(127);
        Integer int2 = 127;
        Integer int6 = 127;
        System.out.println(int1 == int2);
        System.out.println(int6 == int2);

        Integer int3 = Integer.valueOf(128);
        Integer int4 = 128;
        Integer int5 = 128;
        System.out.println(int3 == int4);
        System.out.println(int5 == int4);
    }

    /**
     * 函数动态获取字符串, 无法优化
     * @return 字符串
     */
    private static String getString(){
        return "orz";
    }
}
